package org.rcy.framework.data.datasource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.sql.DataSource;
import java.sql.SQLException;

public class DataSourceChangeListener implements ApplicationContextAware {

	private static Logger logger = LoggerFactory.getLogger(DataSourceChangeListener.class);

	private ApplicationContext applicationContext;

	public void onDataSourceChange(DataSource dataSource) {
		try {
			SimulateDataSource simulateDataSource = applicationContext.getBean(SimulateDataSource.class);
			simulateDataSource.setDelegate(dataSource);
		} catch (NoSuchBeanDefinitionException e) {
			logger.error(e.getMessage());
		}

		SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
		DatabaseIdProvider databaseIdProvider = applicationContext.getBean(DatabaseIdProvider.class);
		Configuration configuration = sqlSessionFactory.getConfiguration();
		try {
			configuration.setDatabaseId(databaseIdProvider.getDatabaseId(dataSource));
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
		}

	}

	

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}